
package com.kaciula.letsdoit.ui;

import com.kaciula.letsdoit.R;
import com.kaciula.letsdoit.db.WastesDbAdapter;
import com.kaciula.utils.StorageHelper;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class MappingActivity extends ListActivity implements FilterQueryProvider {

    private WastesDbAdapter mDbHelper;

    private Cursor mWastesCursor;

    private PreferenceHelper mPrefHelper;

    /* Request codes */
    private static final int REQ_CODE_ADD_WASTE = 0;

    private static final int REQ_CODE_EDIT_WASTE = 1;

    private static final int REQ_CODE_LOGIN = 2;

    private static final int REQ_CODE_UPLOAD = 3;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wastes_list);

        mPrefHelper = ((MyApplication) getApplicationContext()).getPrefHelper();

        fillData();

        registerForContextMenu(getListView());
    }

    @Override
    protected void onDestroy() {
        mDbHelper.close();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_waste:
                startAddWaste();
                return true;
            case R.id.upload_wastes:
                startLogin(-1);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info;

        switch (item.getItemId()) {
            case R.id.delete_waste:
                info = (AdapterContextMenuInfo) item.getMenuInfo();
                deleteWaste(info.id);
                return true;
            case R.id.upload_waste:
                info = (AdapterContextMenuInfo) item.getMenuInfo();
                startLogin(info.id);
                return true;
            case R.id.view_on_map:
                info = (AdapterContextMenuInfo) item.getMenuInfo();
                startMap(info.id);
                return true;
        }

        return super.onContextItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (resultCode == Activity.RESULT_CANCELED) {
            switch (requestCode) {
                case REQ_CODE_ADD_WASTE:
                    long id = mDbHelper.fetchFutureId();
                    deletePics(id);
                    break;
                default:
                    break;
            }
            return;
        }

        if (resultCode != Activity.RESULT_OK)
            return;

        switch (requestCode) {
            case REQ_CODE_ADD_WASTE:
                Toast.makeText(this, R.string.waste_added, Toast.LENGTH_SHORT).show();
                break;
            case REQ_CODE_EDIT_WASTE:
                Toast.makeText(this, R.string.waste_saved, Toast.LENGTH_SHORT).show();
                break;
            case REQ_CODE_LOGIN:
                long id = -1;

                if (intent != null) {
                    Bundle extras = intent.getExtras();

                    if (extras != null) {
                        id = extras.getLong(WastesDbAdapter.KEY_ROWID);
                    }
                }

                startUpload(id);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Intent intent = new Intent(this, WasteEditActivity.class);
        intent.putExtra(WastesDbAdapter.KEY_ROWID, id);
        startActivityForResult(intent, REQ_CODE_EDIT_WASTE);
    }

    @Override
    public Cursor runQuery(CharSequence constraint) {
        final StringBuilder buffer = new StringBuilder();

        if (constraint == null)
            constraint = "";
        buffer.append("'%").append(constraint).append("%'");

        mWastesCursor = mDbHelper.fetchWastes(buffer.toString());
        startManagingCursor(mWastesCursor);

        return mWastesCursor;
    }

    private void fillData() {
        mDbHelper = new WastesDbAdapter(this);
        mDbHelper.open();

        mWastesCursor = mDbHelper.fetchAllWastes();
        startManagingCursor(mWastesCursor);

        // Create an array to specify the fields we want to display in the list
        String[] from = new String[] {
            WastesDbAdapter.KEY_ROWID
        };

        // and an array of the fields we want to bind those fields to (in this
        // case just text1)
        int[] to = new int[] {
            android.R.id.text1
        };

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter wastes = new WastesCursorAdapter(this, R.layout.wastes_list_item,
                mWastesCursor, from, to);
        wastes.setFilterQueryProvider(this);
        setListAdapter(wastes);
    }

    private void startAddWaste() {
        Intent intent = new Intent(this, WasteEditActivity.class);
        startActivityForResult(intent, REQ_CODE_ADD_WASTE);
    }

    private void deleteWaste(long id) {
        boolean deleted = mDbHelper.deleteWaste(id);

        deletePics(id);

        Toast.makeText(this, deleted ? R.string.waste_deleted : R.string.waste_not_deleted,
                Toast.LENGTH_SHORT).show();

        mWastesCursor.requery();
    }

    private void deletePics(long id) {
        String picPath1 = mPrefHelper.getPicPath(id, 1);
        StorageHelper.deleteFile(picPath1);

        String picPath2 = mPrefHelper.getPicPath(id, 2);
        StorageHelper.deleteFile(picPath2);
    }

    private void startLogin(long id) {
        Intent intent = new Intent(this, LoginActivity.class);
        if (id > 0) {
            intent.putExtra(WastesDbAdapter.KEY_ROWID, id);
        }
        startActivityForResult(intent, REQ_CODE_LOGIN);
    }

    private void startUpload(long id) {
        Intent intent = new Intent(this, UploadActivity.class);
        if (id > 0) {
            intent.putExtra(WastesDbAdapter.KEY_ROWID, id);
        }
        startActivityForResult(intent, REQ_CODE_UPLOAD);
    }

    private void startMap(long id) {
        Intent intent = new Intent(this, WasteMapActivity.class);

        Cursor waste = mDbHelper.fetchWaste(id);
        if (waste.moveToFirst()) {
            intent.putExtra(WastesDbAdapter.KEY_ROWID, waste.getLong(waste
                    .getColumnIndexOrThrow(WastesDbAdapter.KEY_ROWID)));
            intent.putExtra(WastesDbAdapter.KEY_LAT, waste.getDouble(waste
                    .getColumnIndexOrThrow(WastesDbAdapter.KEY_LAT)));
            intent.putExtra(WastesDbAdapter.KEY_LONG, waste.getDouble(waste
                    .getColumnIndexOrThrow(WastesDbAdapter.KEY_LONG)));
        }

        startActivity(intent);
    }
}
